package flexibility;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.swing.JFileChooser;
import javax.swing.JFrame;

import com.mysql.jdbc.Blob;
import com.sun.rowset.CachedRowSetImpl;

import basic.ClientConsole;

public class downloadManager extends JFrame {

	///////////////////////////////////////////////////
	/*This class gets 2 parameters for constructor:
	 * ClientConsole conn - connection to server
	 * Integer fileID -  fileID you want to download from 'files' table 
	 */
	//////////////////////////////////////////////////
	private static final long serialVersionUID = 1L;
	private ClientConsole connection;
	private Integer file_id;
	private CachedRowSetImpl crs;
	private String directoryPath;
	private String filename;
	private String filePath;
	private Integer fileSize;
	byte[] byteArray;
	private showMessage msg = new showMessage();
	
	public downloadManager(ClientConsole conn, Integer fileID){
		connection=conn;
		file_id=fileID;
	}
	
	//Method to select the directory where you want to save a file
	public boolean selectDirectory(){
		 JFileChooser fileChooser = new JFileChooser();
		 fileChooser.setCurrentDirectory(null);
		 fileChooser.setDialogTitle("Select directory");
		 fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		 fileChooser.setMultiSelectionEnabled(false);
		 
		 // disable the "All files" option.
		 fileChooser.setAcceptAllFileFilterUsed(false);
		 
		 File fileTemp = new File("");
		 
		 if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
			  
			 fileTemp=fileChooser.getSelectedFile();
			 //fileTemp.exists()
			 directoryPath=fileTemp.getAbsolutePath().concat("\\");
					 
			 System.out.println("The selected directory is: " 
		         +  directoryPath);
		      }
		 else {
		      directoryPath="";
		      return false;
		      }
		
		 return true;
	}
	
	//Method that downloads the file according to fileID and saves it in the selected directory
	public void downloadFile(){
		boolean success=false;
		success=this.selectDirectory();
		if (success==false){
			//msg.showMessages(this, "The selected directory is wrong", "Download error", 1);
			this.dispose();
		}
		else{
			userData fileData = new userData();
			fileData.deleteAll();
			fileData.addData(42); // fileData[0]=query ID
			fileData.addData(1);//fileData[1]=type - read data from DB
			fileData.addData(file_id);// fileData[2]=file_id
			connection.acceptMsg(fileData); // this submits the query to the server
			crs = connection.getResults();// this will get the results from the server
					
			try
		    {
				//Get the results of the download query
				crs.next();
				filename=crs.getString(1);
				filePath=directoryPath+filename;
				System.out.println(filePath);
				fileSize=crs.getInt(2);
				byteArray = new byte[fileSize];	 //get file size
				byteArray=crs.getBytes(3);		//get file data
				File file = new File(filePath);
				FileOutputStream  outStream = new FileOutputStream(file);
				BufferedOutputStream bos = new BufferedOutputStream(outStream);
				bos.write(byteArray);	//write data into the file according to filePath
				msg.showMessages(this, "The file "+filename+" was saved in "+directoryPath, "Download Report", 2);
		 		bos.flush();
				bos.close();
				outStream.close();
		    }
		    catch (Exception e)
		    {
		      e.printStackTrace();
		      System.out.println("ERROR: Unable to export to :  "+filePath);
		      msg.showMessages(this, "Can't download the file", "Download error", 1);
		    }
		}		
	}
}
